package com.lin.missyou.service;

import com.lin.missyou.core.enumeration.CouponStatus;
import com.lin.missyou.exception.http.NotFoundException;
import com.lin.missyou.exception.http.ParameterException;
import com.lin.missyou.model.Activity;
import com.lin.missyou.model.Coupon;
import com.lin.missyou.model.UserCoupon;
import com.lin.missyou.repository.ActivityRepository;
import com.lin.missyou.repository.CouponRepository;
import com.lin.missyou.repository.UserCouponRepository;
import com.lin.missyou.util.CommonUtil;
import com.lin.missyou.vo.CouponPureVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service
public class CouponService {

    @Autowired
    private CouponRepository couponRepository;

    @Autowired
    private ActivityRepository activityRepository;

    @Autowired
    private UserCouponRepository userCouponRepository;

    public List<Coupon> getByCategory(Long cid) {
        Date now = new Date();

        System.out.println(cid);
        System.out.println(now);
        return couponRepository.findByCategory(cid, now);

    }

    public List<Coupon> getWholeStoreCoupons() {
        return couponRepository.getCouponByWholeStore(true, new Date());
    }

    public void collectOneCoupon(Long uid, Long couponId) {
        // 1.判断coupon是否存在
        this.couponRepository
                .findById(couponId)
                .orElseThrow(() -> new NotFoundException(40003));

        // 2.判断coupon是否过期
        Activity activity = this.activityRepository
                .findByCouponListId(couponId)
                .orElseThrow(() -> new NotFoundException(40010));
        Date now = new Date();
        Boolean dateValid = CommonUtil.isDateValid(now, activity.getStartTime(), activity.getEndTime());
        if (!dateValid) {
            throw new ParameterException(40005);
        }

        // 3.判断优惠卷是否被领取
        userCouponRepository.findByUserIdAndCouponId(uid, couponId)
                .ifPresent((uc) -> {
                    throw new ParameterException(40006);
                });


        UserCoupon userCoupon = UserCoupon.builder()
                .userId(uid)
                .couponId(couponId)
                .createTime(now)
                .status(CouponStatus.AVAILABLE.getValue())
                .build();
        // 4.   记录用户的优惠卷
        userCouponRepository.save(userCoupon);
    }

    public List<Coupon> getMyAvailableCoupons(Long uid) {
        return this.couponRepository.findMyAvailableCoupon(uid, new Date());
    }

    public List<Coupon> getMyUsedCoupons(Long uid) {
        return this.couponRepository.findMyUsedCoupon(uid, new Date());

    }

    public List<Coupon> getMyExpiredCoupons(Long uid) {
        return this.couponRepository.findMyExpiredCoupon(uid, new Date());

    }

}
